[bits 16]
[org 0]
 ; STAGE 3 is loaded to 0x2000:0000
start:
	mov ax,cs
	mov ds,ax
	mov es,ax
	;jc offsetread; if carry flag was set, then this is an offset read!
	mov si, welcome ; print welcome message
	call print
	mov ax, 0x2700
	mov es, ax
	mov al, 1 ; number of sectors
	mov bx,0
	mov dl, 80h ; drive
	mov dh,0 ; head
	mov ch,0 ; track
	mov cl, 4 ; sector
	mov ah, 2 ; fREAD
	int 0x13
	
	mov si, sectorloaded
	call print
	; processing
	mov al, [ES:BX]
	mov byte [0x2501], al
	cmp byte [0x2501], 0x02 ; check for version
	jne versionfail
	; version OK
	mov si, readingdrivename
	call print
	;xor EBX, EBX
	xor ECX, ECX
	mov ah, 0x0E
readdrivename:
	cmp BX, 0x06
	je donename
	mov byte al, [ES:0x02 + BX]
	mov byte [0x2500 + 0x03 + BX], al
	inc BX
	int 0x10
	jmp readdrivename
donename:
	call newline
	mov si, readfilestr
	call print
	; first get length
	mov byte al, [ES:0x08]
	cmp al, 0x00
	mov cl, al
	je filenotfound
	xor EBX, EBX
readff: ; file flags
	mov byte al, [ES:0x09] ; al now has the flags
	test al, 0x01 ; get exec flag
	jz filenotfound
	jmp readfn
readfn: ; filename
	cmp EBX, 0x06
	je readfd
	mov ah, 0x0E
	mov byte al, [ES:0x0A + EBX]
	int 0x10
	inc EBX
	jmp readfn
readfd: ; filedata
	xor EBX, EBX
	mov ax, 0x2300
	mov gs, ax
readfd2:
	cmp bl, cl
	je readfdd
	mov byte dl, [ES:0x10 + EBX]
	mov byte [GS:BX], dl
	je readfd2
readfdd:
	call newline
	jmp 0x2700:0000
	
offsetread:
	mov si, epicity
	call print
	XOR EDX, EDX
	mov byte dx, [0x997] ; move the offset to DX
	clc
	jmp start
	
versionfail:
	mov si, wver
	call print
	jmp back
filenotfound:
	mov si, wfile
	call print
back:
	stc
	jmp 0x1000:0000
hang:
	call hang
	
; ============== FUNCTIONS ==================== ;
; PRINT STRING
print:
	mov bp,sp
	cont:
		lodsb
		or al,al
		jz dne
		mov ah,0x0e
		;mov bx,0
		int 10h
		jmp cont
dne:
	mov sp,bp
	ret
	
; ==============

; PRINT NEWLINE
newline:
        mov si, newlinechar
        call print
        retn
; =============

; ====================== DATA ==================== ;
newlinechar db 0Dh, 0Ah, 0
welcome db 'LevFS is being loaded...',10,13,0
sectorloaded db 'LevFS sector was loaded.',10,13,0
wver db 'Wrong version of LevFS!',0
wfile db 'File length 0', 0
readingdrivename db 'Reading Drive name...',10,13,0
readfilestr db 'Reading file...',10,13,0
filedone db 'Jumping to file...', 10,13,0
epicity db 'Epic!',10,13,0
times 512 - ($-$$) db 0